package com.edu.util.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZipUtil.class);

    public static void unzip(File sourceFile, File descDir, Charset charSet) throws Exception {
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(sourceFile), charSet)) {
            ZipEntry entry = null;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                try {
                    File descFile = new File(descDir, entry.getName());
                    try (FileOutputStream fos = new FileOutputStream(descFile); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                        byte[] bytes = new byte[1024];
                        int len;
                        while ((len = zipInputStream.read(bytes)) != -1) {
                            bos.write(bytes, 0, len);
                        }
                        bos.flush();
                    } catch (Exception e) {
                        throw e;
                    }
                } finally {
                    zipInputStream.closeEntry();
                }
            }
        } catch (Exception e) {
            LOGGER.error("unzip error: {}", e.getMessage());
            throw e;
        }
    }
}
